<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-row style="margin-bottom: 20px">
          <!-- 第一行面包屑导航 -->
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/User/NewsManage' }"
              >新闻管理</el-breadcrumb-item
            >
            <el-breadcrumb-item>已发表新闻</el-breadcrumb-item>
          </el-breadcrumb>
        </el-row>
        <!-- 第二行：卡片 -->
        <el-row>
          <el-card class="box-card">
            <!-- 第一行：搜索 -->
            <el-row style="margin-bottom: 20px">
              <el-col :span="12">
                <el-input
                  placeholder="请输入要找的新闻标题 "
                  v-model="searchWords"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="handleSearch"
                  ></el-button>
                </el-input>
              </el-col>
            </el-row>
            <!-- 第二行：table表格 -->
            <el-row style="margin-bottom: 20px">
              <el-table
                :data="pagedNews"
                border
                stripe
                style="width: 100%; font-size: 14px"
              >
                <el-table-column
                  fixed
                  label="序号"
                  align="center"
                  type="index"
                  width="40px"
                >
                </el-table-column>
                <el-table-column
                  v-if="false"
                  align="center"
                  fixed
                  label="新闻id"
                  prop="id"
                  width="40px"
                >
                </el-table-column>
                <el-table-column
                  fixed
                  align="center"
                  prop="title"
                  label="标题"
                  width="150"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="describe"
                  label="新闻简介"
                  width="200px"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  label="大图"
                  prop="titlePic"
                  width="160px"
                >
                  <!-- <img :src="bigPic" alt=""> -->
                  <template slot-scope="scope">
                    <img
                      :src="baseImgURL + scope.row.titlePic"
                      alt=""
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="newsCategoryId"
                  label="新闻分类id"
                  width="100px"
                  v-if="false"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="newsCategoryName"
                  label="新闻分类"
                  width="100px"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="newsStausName"
                  align="center"
                  label="新闻状态"
                  width="80"
                >
                </el-table-column>
                <el-table-column
                  fixed="right"
                  label="操作"
                  align="center"
                  width="170"
                >
                  <template slot-scope="scope">
                    <el-button
                      icon="el-icon-search"
                      @click="handleClick(scope.row)"
                      circle
                    ></el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      @click="editClick(scope.row)"
                      circle
                    ></el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteClick(scope.row)"
                      circle
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
            <!-- 第三行：分页 -->
            <el-row>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[3, 5, 10, 20]"
                :page-size="currentSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </el-row>
          </el-card>
          <!-- 编辑对话框 -->
          <el-dialog title="编辑新闻" :visible.sync="editDialogVisiable">
            <editNewsform
              :editformData="editformData"
              @cancelForm="userCancleHandler"
              @UpdateData="UpdateDataHandler"
            ></editNewsform>
          </el-dialog>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import editNewsform from "./editNews.vue";
import News from "@/api/News.js";
const news = new News();
export default {
  data() {
    return {
      baseImgURL: "http://121.196.246.105:4000/#/News/TitlePic/",

      searchWords: "", //搜索关键字

      news: [], //数据源
      //   分页

      pagedNews: [],
      currentPage: 1,
      currentSize: 5,
      total: 0,

      //   编辑对话框
      editDialogVisiable: false,
      editformData: {},
    };
  },
  methods: {
    // table表格行事件
    handleClick(row) {
      // 查看新闻事件
      this.$router.push("/#/News/" + row.id);
    },

    editClick(row) {
      this.editDialogVisiable = true;
      // 将当前row的数据传到editform中
      // console.log(row);
      this.editformData = row;
      // console.log(this.editformData);
    },

    // 用户取消控制事件
    userCancleHandler() {
      this.editDialogVisiable = false;
    },

    async UpdateDataHandler() {
      this.editDialogVisiable = false;
      // 更新数据
      const newsFromDatabase = await this.GetALLNewsInShow();
      
      // 进一步封装news里的newsCategoryName参数
      const newsCategories = this.$store.state.newsCategories;
      for (var i = 0; i < newsFromDatabase.length; i++) {
        for (var j = 0; j < newsCategories.length; j++) {
          if (newsFromDatabase[i].newsCategoryId === newsCategories[j].id) {
            newsFromDatabase[i].newsCategoryName = newsCategories[j].name;
          }
        }
      }
      this.news = newsFromDatabase;

      this.total = this.news.length;
      this.pagedNews = this.GetPagedNews();
    },



    // ~~~~~~~~~~~~~~~~~~~~点击删除事件~~~~~~~~~~~~~~~~~~~~
    // 点击删除事件
    async deleteClick(row) {
      if (confirm("确认删除此项吗？")) {
        // 先删除，根据删除返回结果再更新数据
        const token = this.$store.state.token;
        const response = await news.DeleteNews(row.id, token);
        console.log(response);
        if (response.data) {
          // 操作成功，更新数据
          this.$message.success("操作成功！");

          const newsFromDatabase = await this.GetALLNewsInShow();
          // 进一步封装news里的newsCategoryName参数
          const newsCategories = this.$store.state.newsCategories;
          for (var i = 0; i < newsFromDatabase.length; i++) {
            for (var j = 0; j < newsCategories.length; j++) {
              if (newsFromDatabase[i].newsCategoryId === newsCategories[j].id) {
                newsFromDatabase[i].newsCategoryName = newsCategories[j].name;
              }
            }
          }
          this.news = newsFromDatabase;

          this.total = this.news.length;
          this.pagedNews = this.GetPagedNews();
        } else {
          //操作失败
          this.$message.error("服务器错误，操作失败！");
        }
      }
    },
    // ~~~~~~~~~~~~~~~~~~~~点击删除事件~~~~~~~~~~~~~~~~~~~~

    // ~~~~~~~~~~~~~~~~~~~~分页事件~~~~~~~~~~~~~~~~~~~~
    // 得到当前分类选项下的News
    GetPagedNews() {
      return this.news.slice(
        (this.currentPage - 1) * this.currentSize,
        (this.currentPage - 1) * this.currentSize + this.currentSize
      );
    },
    handleSizeChange(currentSize) {
      this.currentSize = currentSize;
      console.log(currentSize);
      console.log(this.pagedNews);
      this.pagedNews = this.GetPagedNews();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      console.log(currentPage);
      console.log(this.pagedNews);
      this.pagedNews = this.GetPagedNews();
    },
    // ~~~~~~~~~~~~~~~~~~~~分页事件结束~~~~~~~~~~~~~~~~~~~~

    // ~~~~~~~~~~~~~~~~~~~~搜索事件开始~~~~~~~~~~~~~~~~~~~~
    handleSearch() {
      // 搜索事件的逻辑为：用filter函数找出符合条件的news组合再重新赋值给PagedNews

      const targetNews = this.news.filter(
        (n) => n.title.indexOf(this.searchWords) != -1
      );
      console.log(targetNews);

      this.total = targetNews.length;
      this.pagedNews = targetNews.slice(
        (this.currentPage - 1) * this.currentSize,
        (this.currentPage - 1) * this.currentSize + this.currentSize
      );
    },

    // ~~~~~~~~~~~~~~~~~~~~搜索事件结束~~~~~~~~~~~~~~~~~~~~

    // 拿到当前AppUser下的所有InshowNews，赋值给tabledata
    async GetALLNewsInShow() {
      const appUserId = this.$store.state.id;
      const response = await news.GetNewsByAppUserId(appUserId);
      // console.log(response);
      return response.data;
    },
  },
  // computed:{
  //   pagedNews:function(){
  //     return this.GetPagedNews();
  //   }
  // },
  //拿到vuex中的数据，将其赋值给tabledata
  async mounted() {
    // const news = await this.$store.getters.getNews.filter(
    //   (n) => n.authorId == 0
    // );
    // this.total = news.length;
    // //默认拿到第一页的内容
    // this.news = news.splice(1, this.currentSize);
    const newsFromDatabase = await this.GetALLNewsInShow();
    // 进一步封装news里的newsCategoryName参数
    const newsCategories = this.$store.state.newsCategories;
    for (var i = 0; i < newsFromDatabase.length; i++) {
      for (var j = 0; j < newsCategories.length; j++) {
        if (newsFromDatabase[i].newsCategoryId === newsCategories[j].id) {
          newsFromDatabase[i].newsCategoryName = newsCategories[j].name;
        }
      }
    }
    this.news = newsFromDatabase;

    this.total = this.news.length;
    this.pagedNews = this.GetPagedNews();
  },
  components: {
    editNewsform,
  },
};
</script>